//
//  NetworkTools.swift
//  AFNetworking 封装
//
//  Created by 张海峰 on 2017/7/24.
//  Copyright © 2017年 张海峰. All rights reserved.
//

import AFNetworking
enum RequestType {
    case GET
    case POST
}
class NetworkTools: AFHTTPSessionManager {
    // let 是线程安全的，即使多线程调用，也只保证创建一次
    static  let shareInstance : NetworkTools = {
    let tools = NetworkTools()
  tools.responseSerializer.acceptableContentTypes?.insert("text/html")
    tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
}
//MARK:-   封装请求方法
extension NetworkTools{
    func request(methodType: RequestType, urlString : String , parameters :[String : AnyObject], finished :@escaping ( _ result : Any?,_ error : Error?) -> ())
    {
        //定义成功的回调闭包
        let successCallBack = {(task:URLSessionDataTask,result : Any?) in
            finished(result, nil)
        }
        //定义失败的回调闭包
        let failureCallBack = {(task:URLSessionDataTask?,error : Error?) in
            finished(nil, error)
        }
        if methodType == .GET {
            get(urlString, parameters: parameters, progress: nil,
                success:successCallBack,
                failure: failureCallBack
            )
        }
        else{
            post(urlString, parameters: parameters, progress: nil,  success:successCallBack,
                 failure: failureCallBack
            )
        }
    }
}
//MARK:-   请求首页数据
extension NetworkTools{
   
    
    func loadStatuses(finished : @escaping (_ result : [String : Any]?, _ error : NSError? ) -> ()) {
         let urlString = "https://www.i-fbs.com/api.php?app=collocation&act=getCollocationData"
        let parameters = ["app_id":"Yamei","app_secret":"5b33681a3b61c26e00a3e3c070e94ec4","page":"1","user_id":""]
       request(methodType: .POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) in
        guard let resultDict = result as? [String :AnyObject]
            else {
                finished(nil, error as NSError?)
                return
        }
        finished(resultDict, error as NSError?)
        }
    }
}
